﻿using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Threading;
using System.Windows.Forms;

using HelperLibrary;
using MasterLibrary.IO;
using MasterLibrary.Logging;
using MasterLibrary.Windows.Forms;
using MasterLibrary.Cryptography;
using MasterLibrary.IO.XML;

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip; 

namespace BackupLibrary
{
    public class BackupClass
    {
        private ApplicationLogger logger;

        public event EventHandler<BackupEventArgs> UpdateProgress;
        private void OnUpdateProgress(BackupEventArgs e)
        {
            EventHandler<BackupEventArgs> ev = UpdateProgress;
            if (ev != null) ev(this, e);
        }

        public event EventHandler<BackupEventArgs> UpdateFileProgress;
        private void OnUpdateFileProgress(BackupEventArgs e)
        {
            EventHandler<BackupEventArgs> ev = UpdateFileProgress;
            if (ev != null) ev(this, e);
        }

        public BackupClass()
        {
            this.logger = ApplicationLogger.Singleton();
        }

        private FileCopyClass copyClass;
        private BackupState error;

        public BackupState CreateBackup(BackupContainer Container, Form mainform)
        {
            string DestinationPath = Globals.appConfig.DestinationPath;
            error = BackupState.OK;

            this.logger.Log(3, "BackupClass", "-----------------------------");
            this.logger.Log(3, "BackupClass", "Backup Process started ...");
            this.logger.Log(3, "BackupClass", "-----------------------------");

            #region Kill running Applications
            try
            {
                foreach (string app in Container.CloseProcessItems)
                {
                    MasterLibrary.Windows.SystemMethods.KillProcess(app);
                }
            }
            catch
            {
                this.logger.Log(1, "BackupClass", "Processes could not be killed.");
                error = BackupState.Error;
            }
            #endregion

            #region Create Destination Folder
            if (DestinationPath.Length > 0)
            {
                if (!Directory.Exists(DestinationPath))
                {
                    try
                    {
                        Directory.CreateDirectory(DestinationPath);
                    }
                    catch
                    {
                        this.logger.Log(1, "BackupClass", "Destination Folder could not be created");
                        error = BackupState.Error;
                    }
                }
            }
            else
            {
                this.logger.Log(1, "BackupClass", "No Destination Folder is declared.");
                error = BackupState.Error;
            }
            #endregion

            if (error == BackupState.OK)
            {
                foreach (BackupItem item in Container.BackupItems)
                {
                    if (error == BackupState.OK)
                    {
                        if (item.Active)
                        {
                            if (Globals.appConfig.DeleteEmptyFolder)
                            {
                                bool result = this.SearchEmptyFolders(item.SourcePath);

                                if (!result)
                                {
                                    error = BackupState.Error;
                                }
                            }

                            if (error == BackupState.OK)
                            {
                                try
                                {
                                    copyClass = new FileCopyClass(item.SourcePath, AddSourceFolder(item.SourcePath, DestinationPath, item.AddSourceFolder));

                                    if (item.FileType == ItemFileType.BackupAll)
                                    {
                                        copyClass.SearchPatternType = FileCopyClass.SearchPatternTypes.IgnorePattern;
                                        copyClass.SearchPattern = "";
                                    }
                                    if (item.FileType == ItemFileType.ExcludeContext)
                                    {
                                        copyClass.SearchPatternType = FileCopyClass.SearchPatternTypes.ExcludePattern;
                                        copyClass.SearchPattern = item.ExcludeContext;
                                    }
                                    if (item.FileType == ItemFileType.IncludeContext)
                                    {
                                        copyClass.SearchPatternType = FileCopyClass.SearchPatternTypes.IncludePattern;
                                        copyClass.SearchPattern = item.IncludeContext;
                                    }

                                    copyClass.ExcludeItems = Container.ExcludedItems;

                                    copyClass.CopyCanceled += new EventHandler(copyClass_CopyCanceled);
                                    copyClass.CopyFeedback += new EventHandler<CopyFeedbackEventArgs>(copyClass_CopyFeedback);
                                    copyClass.Copy(true);
                                }
                                catch
                                {
                                    error = BackupState.Error;
                                }
                            }
                        }
                    }
                }

                if (error == BackupState.OK)
                {
                    this.OnUpdateFileProgress(new BackupEventArgs(1, 1, "Dateien erfolgreich gesichert ...", 1, 1, ""));
                    this.OnUpdateProgress(new BackupEventArgs(1, 0, "", 1, 0, "Datensicherung wird komprimiert ..."));

                    if (Globals.appConfig.UseCompression)
                    {
                        ZipClass zip = new ZipClass();
                        if (Globals.appConfig.UseCryptography)
                        {
                            zip.CompressDirectory(DestinationPath, "Backup.zip", DestinationPath, RijndaelClass.DecryptString(Globals.appConfig.CryptPass, "prometheus_cryptolib"));
                        }
                        else
                        {
                            zip.CompressDirectory(DestinationPath, "Backup.zip", DestinationPath);
                        }
                    }
                }

                copyClass = null;
            }

            this.logger.Log(3, "BackupClass", "-----------------------------");
            this.logger.Log(3, "BackupClass", "Backup Process ended ...");
            this.logger.Log(3, "BackupClass", "-----------------------------");

            return error;
        }

        private void copyClass_CopyCanceled(object sender, EventArgs e)
        {
            this.error = BackupState.Canceled;
        }

        private void copyClass_CopyFeedback(object sender, CopyFeedbackEventArgs e)
        {
            this.OnUpdateFileProgress(new BackupEventArgs(e.TotalFileCount, e.CurrentFileIndex, e.CurrentFileName, e.TotalFileSize, e.CopiedSize, e.CopyPath));
            this.OnUpdateProgress(new BackupEventArgs(e.TotalFileCount, e.CurrentFileIndex, e.CurrentFileName, e.TotalFileSize, e.CopiedSize, e.CopyPath));
        }

        public void SendCancelEvent()
        {
            if (this.copyClass != null)
            {
                this.copyClass.CancelCopy();
            }
        }

        private bool SearchEmptyFolders(string FolderPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(FolderPath);

                foreach (DirectoryInfo val in dir.GetDirectories())
                {
                    SearchEmptyFolders(val.FullName);
                }

                if (dir.GetDirectories().Length <= 0 && dir.GetFiles().Length <= 0)
                    dir.Delete();
            }
            catch
            {
                return false;
            }

            return true;
        }

        private string AddSourceFolder(string SourceFolder, string DestinationPath, bool Add)
        {
            if (Add)
            {
                string[] arr = SourceFolder.Split('\\');

                if (DestinationPath.Substring(DestinationPath.Length - 1, 1).Equals("\\"))
                {
                    DestinationPath = string.Concat(DestinationPath, arr[arr.Length - 1]);
                }
                else
                {
                    DestinationPath = string.Concat(DestinationPath, "\\", arr[arr.Length - 1]);
                }
            }
            return DestinationPath;
        }

        public bool SaveBackupContainer(BackupContainer Container)
        {
            try
            {
                XmlHelper.Serialize<BackupContainer>(Globals.BackupPath, Container);
            }
            catch
            {
                this.logger.Log(0, "BackupClass", "Error while saving configuration!");
                return false;
            }
            return true;
        }

        public BackupContainer LoadBackupContainer()
        {
            BackupContainer Container;

            try
            {
                XmlHelper.Deserialize<BackupContainer>(Globals.BackupPath, out Container);
            }
            catch
            {
                this.logger.Log(1, "BackupClass", "Error while loading configuration!");
                return new BackupContainer();
            }
            return Container;
        }
    }
}
